using System.Text;

namespace Coding4Fun.BluetoothPanoHead
{
    public class CommandParser
    {
        private CommandQueue Commands = new CommandQueue();
        private readonly StringBuilder _command = new StringBuilder();
        private System.Object lockThis = new System.Object();

        /// <summary>
        /// Takes incoming data and appends to the buffer.  Then buffer is parsed for commands, with recognized commands going into the queue
        /// Wrapped with a lock object to prevent threading issues
        /// </summary>
        /// <param name="value">Incoming data.</param>
        public void AddString(string value)
        {
            lock (lockThis)
            {
                _command.Append(value);

                Parse();
            }
        }

        /// <summary>
        /// Pops the oldest command out of the queue.  
        /// Wrapped with a lock object to prevent threading issues
        /// </summary>
        /// <returns>Returns the oldest ControlCommand</returns>
        public ControlCommand Dequeue()
        {
            lock (lockThis)
            {
                return Commands.Dequeue();
            }
        }

        /// <summary>
        /// Gets the count of commands in the queue.
        /// Wrapped with a lock object to prevent threading issues
        /// </summary>
        /// <value>
        /// The number of commands left in the queue.
        /// </value>
        public int Count { 
            get
            {
                lock (lockThis)
                {
                    return Commands.Count;
                }
            }
        }

        /// <summary>
        /// Walk through the incoming buffer and pull out commands that start with "@" and end with "#"
        /// </summary>
        public void Parse()
        {
            string foo = _command.ToString();
            int start = foo.IndexOf('@');

            if (start >= 0)
            {
                foo = foo.Substring(start);

                int end = foo.IndexOf('#');
                if (end > 0)
                {
                    string cmd = foo.Substring(0, end + 1);

                    var controlCommand = new ControlCommand(cmd);

                    Commands.Enqueue(controlCommand);
                    foo = foo.Substring(end + 1);
                }
                _command.Clear();
                _command.Append(foo);
            }
            else
            {
                _command.Clear();
            }
        }
    }
}
